package com.example.bookmanager;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.JavaType;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnKeyListener;
import android.graphics.drawable.AnimationDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request.Method;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.xuyang.other.BookBean;
import com.xuyang.other.Flags;
import com.xuyang.other.ProgressDialog;
//图书浏览页面
public class BrowseActivity extends Activity {
	private PullToRefreshListView pullToRefresh;
	ArrayList<BookBean> list=new ArrayList<BookBean>();
	private MyAdapter adapter;
	private TextView txtBookCategory;
	private RequestQueue mQueue;
	private AlertDialog dialog;
	private String bookCategory;
	private ImageView imgFinish;
	private StringRequest mRequest;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_browse);
		findViewsById();
		init();
		setPullToRefresh();
	}
	//找到所有控件
	private void findViewsById() {
		pullToRefresh = (PullToRefreshListView)findViewById(R.id.pullToRefresh);
		txtBookCategory=(TextView) findViewById(R.id.txt_book_category);
		imgFinish=(ImageView) findViewById(R.id.img_finish);
	}
	//程序初始化工作
	private void init() {
		imgFinish.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
			}
		});
		bookCategory=getIntent().getExtras().getString("bookCategory");
		txtBookCategory.setText(bookCategory);
		mQueue=Volley.newRequestQueue(this);
		String url=Flags.URL.replace("FIRST", String.valueOf(list.size())).replace("LAST", String.valueOf(list.size()+20)).replace("CATEGORY",URLEncoder.encode(bookCategory));
		//刚进入的时候加载数据
		mRequest=new StringRequest(url,
		new Response.Listener<String>() {
			@Override
			public void onResponse(final String response) {
				if (response.equals("over")) {
					dialog.dismiss();
					Toast.makeText(getApplicationContext(), "已是最后一本", 0).show();
					return ;
				}
				//处理线程
				new AsyncTask<Void, Void, Void>(){
					@Override
					protected Void doInBackground(Void... params) {
						ObjectMapper mapper=new ObjectMapper();
						JavaType type=mapper.getTypeFactory().constructParametricType(ArrayList.class, BookBean.class);
						try {
							ArrayList<BookBean> arrayList=mapper.readValue(response, type);
							list.addAll(arrayList);
						} catch (JsonParseException e) {
							e.printStackTrace();
						} catch (JsonMappingException e) {
							e.printStackTrace();
						} catch (IOException e) {
							e.printStackTrace();
						}
						return null;
					}
					@Override
					protected void onPostExecute(Void result) {
						adapter.notifyDataSetChanged();
						dialog.dismiss();
					}
				}.execute();
			}
		},
		new Response.ErrorListener() {
			@Override
			public void onErrorResponse(VolleyError error) {
				Toast.makeText(BrowseActivity.this, "网络连接异常", 0).show();
				dialog.dismiss();
			}
		});
		mQueue.add(mRequest);
		dialog=new ProgressDialog(this).getDialog();
		//给加载框设置监听
		dialog.setOnKeyListener(new OnKeyListener() {
			@Override
			public boolean onKey(DialogInterface d, int keyCode, KeyEvent event) {
				 if (keyCode == KeyEvent.KEYCODE_BACK&&event.getAction()==KeyEvent.ACTION_DOWN) {
					 	new AlertDialog.Builder(BrowseActivity.this)
					 	.setTitle("提示")
					 	.setMessage("确定取消加载？")
					 	.setNegativeButton("确定", new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface a, int which) {
								mRequest.cancel();
								dialog.dismiss();
							}
						})
						.setPositiveButton("取消", null)
						.create()
						.show();
			            return false;
			        }
				return false;
			}
		});
	}
	//设置下拉刷新控件的一系列属性
	private void setPullToRefresh() {
		adapter=new MyAdapter(LayoutInflater.from(BrowseActivity.this));
		pullToRefresh.setAdapter(adapter);
		pullToRefresh.setVisibility(View.VISIBLE);
		pullToRefresh.setMode(Mode.PULL_FROM_END);
		pullToRefresh.setOnRefreshListener(new OnRefreshListener<ListView>() {
			@Override
			public void onRefresh(PullToRefreshBase<ListView> refreshView) {
				String url=Flags.URL.replace("FIRST", String.valueOf(list.size())).replace("LAST", String.valueOf(list.size()+20)).replace("CATEGORY",URLEncoder.encode(bookCategory));
				System.out.println(url);		
				StringRequest request=new StringRequest(url,
						new Response.Listener<String>() {
							@Override
							public void onResponse(String response) {
								if (response.equals("over")) {
									pullToRefresh.onRefreshComplete();
									Toast.makeText(getApplicationContext(), "已是最后一本", 0).show();
									return ;
								}
								ObjectMapper mapper=new ObjectMapper();
								JavaType type=mapper.getTypeFactory().constructParametricType(ArrayList.class, BookBean.class);
								ArrayList<BookBean> arrayList;
								try {
									arrayList = mapper.readValue(response, type);
									list.addAll(arrayList);
									adapter.notifyDataSetChanged();
								} catch (JsonParseException e) {
									e.printStackTrace();
								} catch (JsonMappingException e) {
									e.printStackTrace();
								} catch (IOException e) {
									e.printStackTrace();
								}finally{
									//关闭
									pullToRefresh.onRefreshComplete();
								}
							}
						},
						new Response.ErrorListener() {
							@Override
							public void onErrorResponse(VolleyError error) {
								pullToRefresh.onRefreshComplete();
								Toast.makeText(BrowseActivity.this, "刷新失败", 0).show();
							}
						});
						mQueue.add(request);
			}
		});
		pullToRefresh.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Intent intent=new Intent(BrowseActivity.this,BookDetailsActivity.class);
				Bundle bundle=new Bundle();
				bundle.putSerializable("book", list.get(position));
				bundle.putInt("position", position);
				intent.putExtras(bundle);
				startActivityForResult(intent, 10086);
			}
		});
		
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode==10086) {
			BookBean bean=(BookBean) data.getExtras().getSerializable("book");
			int position =data.getExtras().getInt("position");
			list.set(position, bean);
			adapter.notifyDataSetChanged();
		}
	}

	class MyAdapter extends BaseAdapter {
		private LayoutInflater mInflater;
		public MyAdapter(LayoutInflater inflater) {
			mInflater = inflater;
		}
		@Override
		public int getCount() {
			return list.size();
		}
		@Override
		public Object getItem(int position) {
			return list.get(position);
		}
		@Override
		public long getItemId(int position) {
			return position;
		}
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder viewHolder=null;
			if (convertView==null) {
				convertView=mInflater.inflate(R.layout.item_pull_to_refresh, parent, false);
				viewHolder=new ViewHolder();
				viewHolder.txtBookName=(TextView) convertView.findViewById(R.id.txt_book_name);
				viewHolder.txtBookWriter=(TextView) convertView.findViewById(R.id.txt_book_writer);
				viewHolder.imgState=(ImageView) convertView.findViewById(R.id.img_book_state);
				convertView.setTag(viewHolder);
			}else {
				viewHolder=(ViewHolder) convertView.getTag();
			}
				final BookBean bookBean=list.get(position);
				viewHolder.txtBookName.setText(bookBean.getName());
				viewHolder.txtBookWriter.setText(bookBean.getWriter());
				if (bookBean.getState()==0) {
					viewHolder.imgState.setImageResource(R.drawable.book_state_0);
				}else {
					viewHolder.imgState.setImageResource(R.drawable.selector_book_state_1);
				}
				//当点击借阅按钮时
				viewHolder.imgState.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						//如果点击时发现当前状态是0时，不做任何处理
						if (bookBean.getState()==0) {
							return ;
						}
						if (Flags.UserName.equals("")) {
							Toast.makeText(getApplicationContext(), "请先登录", 0).show();
						}else {
							String url=Flags.BORROW_BOOK.replace("BOOKID", String.valueOf(bookBean.getId())).replace("USERNAME", Flags.UserName);
							final StringRequest request=new StringRequest(url,
							new Response.Listener<String>() {
								@Override
								public void onResponse(String result) {
									if (result.equals("borrowed")) {
										Toast.makeText(getApplicationContext(), "该书已被预阅", 0).show();
										bookBean.setState(0);
										adapter.notifyDataSetChanged();
									}else if (result.equals("error")) {
										Toast.makeText(getApplicationContext(), "服务器出错，请重试", 0).show();
									}else if (result.equals("ok")) {
										Toast.makeText(getApplicationContext(), "预阅成功", 0).show();
										bookBean.setState(0);
										adapter.notifyDataSetChanged();
									}
									if (dialog!=null) {
										dialog.dismiss();
									}
								}
							},
							new Response.ErrorListener() {
								@Override
								public void onErrorResponse(VolleyError error) {
									Toast.makeText(getApplicationContext(), "网络连接异常", 0).show();
								}
							});
							mQueue.add(request);
							//出现提示框，提示用户进度
							dialog=new ProgressDialog(BrowseActivity.this).getDialog();
							dialog.setOnKeyListener(new OnKeyListener() {
								@Override
								public boolean onKey(DialogInterface d, int keyCode, KeyEvent event) {
									 if (keyCode == KeyEvent.KEYCODE_BACK&&event.getAction()==KeyEvent.ACTION_DOWN) {
										 	new AlertDialog.Builder(BrowseActivity.this)
										 	.setTitle("提示")
										 	.setMessage("确定取消预阅？")
										 	.setNegativeButton("确定", new DialogInterface.OnClickListener() {
												@Override
												public void onClick(DialogInterface a, int which) {
													request.cancel();
													dialog.dismiss();
												}
											})
											.setPositiveButton("取消", null)
											.create()
											.show();
								            return false;
								        }
									return false;
								}
						});
						}
					}
				});
				
			return convertView;
		}
		class ViewHolder{
			TextView txtBookName,txtBookWriter;
			ImageView imgState;
		}
	}
	
}
